﻿using CommonTools;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HttpHelper;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using WeChatCore;
using WeChatCore.Common;
using WeChatCore.DefineClass;
using WeChatCore.Entity;
using WeChatCore.Enum;
using WindowsWeChat.Common;
using WindowsWeChat.Entity;
using WindowsWeChat.EnumEntity;

namespace WindowsWeChat.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        #region 属性
        /// <summary>
        /// 页面号码
        /// </summary>
        public int PageNumber { get; set; }
        /// <summary>
        /// 当前每页数目
        /// </summary>
        public int PageCount { get; set; }
        /// <summary>
        /// 锁 更新数据用
        /// </summary>
        public static readonly object Locker = new object();

        private Visibility _QRCodeVisibilty = Visibility.Visible;
        /// <summary>
        /// 二维码的可见性
        /// </summary>
        public Visibility QRCodeVisibilty
        {
            get
            {
                return _QRCodeVisibilty;
            }
            set
            {
                _QRCodeVisibilty = value;
                RaisePropertyChanged(() => QRCodeVisibilty);
            }
        }
        private string _ImagePath = string.Empty;
        /// <summary>
        /// 图片路径
        /// </summary>
        public string ImagePath
        {
            get
            {
                return _ImagePath;
            }
            set
            {
                _ImagePath = value;
                RaisePropertyChanged(() => ImagePath);
            }
        }
        private ImageSource _LoginImageSource;
        /// <summary>
        /// 登录图片
        /// </summary>
        public ImageSource LoginImageSource
        {
            get
            {
                return _LoginImageSource;
            }
            set
            {
                _LoginImageSource = value;
                RaisePropertyChanged(() => LoginImageSource);
            }
        }
        private List<MemberListItemEntity> _WeChatContactsList = new List<MemberListItemEntity>();
        /// <summary>
        /// 联系人列表
        /// </summary>
        public List<MemberListItemEntity> WeChatContactsList
        {
            get
            {
                return _WeChatContactsList;
            }
            set
            {
                _WeChatContactsList = value;
                RaisePropertyChanged(() => WeChatContactsList);
            }
        }

        private MemberListItemEntity _CurrentMli = new MemberListItemEntity();
        /// <summary>
        /// 当前联系人
        /// </summary>
        public MemberListItemEntity CurrentMli
        {
            get
            {
                return _CurrentMli;
            }
            set
            {
                _CurrentMli = value;
                RaisePropertyChanged(() => CurrentMli);
            }
        }

        private List<MsgEntity> _MsgList = new List<MsgEntity>();
        /// <summary>
        /// 消息列表
        /// </summary>
        public List<MsgEntity> MsgList
        {
            get
            {
                return _MsgList;
            }
            set
            {
                _MsgList = value;
                RaisePropertyChanged(() => MsgList);
            }
        }
        private List<MsgStoreEntity> _MsgStoreList = new List<MsgStoreEntity>();
        /// <summary>
        /// 消息体存贮
        /// </summary>
        private List<MsgStoreEntity> MsgStoreList
        {
            get
            {
                return _MsgStoreList;
            }
            set
            {
                _MsgStoreList = value;
            }
        }

        private string _SendMsg = string.Empty;
        /// <summary>
        /// 发送的消息
        /// </summary>
        public string SendMsg
        {
            get
            {
                return _SendMsg;
            }
            set
            {
                _SendMsg = value;
                RaisePropertyChanged(() => SendMsg);
            }
        }
        private Visibility _ContentVisibilty = Visibility.Collapsed;
        /// <summary>
        /// 主界面的内容是否可见
        /// </summary>
        public Visibility ContentVisibilty
        {
            get
            {
                return _ContentVisibilty;
            }
            set
            {
                _ContentVisibilty = value;
                RaisePropertyChanged(() => ContentVisibilty);
            }
        }
        private bool _GoupContactsChecked = false;
        /// <summary>
        /// 群联系人
        /// </summary>
        public bool GoupContactsChecked
        {
            get
            {
                return _GoupContactsChecked;
            }
            set
            {
                _GoupContactsChecked = value;
                if (value)
                {
                    WeChatContactsList = WeiChat.SetSplite(ContactType.GroupContact);
                }
                RaisePropertyChanged(() => GoupContactsChecked);
            }
        }
        private bool _PersonChecked = false;
        /// <summary>
        /// 个人联系信息
        /// </summary>
        public bool PersonChecked
        {
            get
            {
                return _PersonChecked;
            }
            set
            {
                _PersonChecked = value;
                if (value)
                {
                    WeChatContactsList = WeiChat.SetSplite(ContactType.PersonContact);
                    ReadMsg();
                }
                RaisePropertyChanged(() => PersonChecked);
            }
        }
        private bool _PublicContacts = false;
        /// <summary>
        /// 公众号
        /// </summary>
        public bool PublicContacts
        {
            get
            {
                return _PublicContacts;
            }
            set
            {
                _PublicContacts = value;
                if (value)
                {
                    WeChatContactsList = WeiChat.SetSplite(ContactType.PublicContact);
                }
                RaisePropertyChanged(() => PublicContacts);
            }
        }
        private FlowDocument _MsgDocument = new FlowDocument();
        /// <summary>
        /// 流文档
        /// </summary>
        public FlowDocument MsgDocument
        {
            get
            {
                return _MsgDocument;
            }
            set
            {
                _MsgDocument = value;
                RaisePropertyChanged(() => MsgDocument);
            }
        }
        private Visibility _SettingVisibility = Visibility.Collapsed;
        /// <summary>
        /// 设置
        /// </summary>
        public Visibility SettingVisibility
        {
            get
            {
                return _SettingVisibility;
            }
            set
            {
                _SettingVisibility = value;
                RaisePropertyChanged(() => SettingVisibility);
            }
        }
        /// <summary>
        /// 表情实体
        /// </summary>
        public Face Faces { get; set; }
        public RichTextBox Rtb { get; set; }
        /// <summary>
        /// 联系人类型
        /// </summary>
        public ContactType CtType { get; set; }
        /// <summary>
        /// 信息段
        /// </summary>
        public Paragraph MsgParagraph { get; set; }
        #endregion

        #region 命令
        private RelayCommand _LeftConerCommand = null;
        /// <summary>
        /// 关闭
        /// </summary>
        public RelayCommand LeftConerCommand
        {
            get
            {
                return _LeftConerCommand ?? (_LeftConerCommand = new RelayCommand(() =>
                {
                }));
            }
        }

        private RelayCommand<string> _ChatCommand = null;
        /// <summary>
        /// 聊天按钮
        /// </summary>
        public RelayCommand<string> ChatCommand
        {
            get
            {
                return _ChatCommand ?? (_ChatCommand = new RelayCommand<string>((p) =>
                {
                    MemberListItemEntity Mli = (from item in WeChatContactsList where item.UserName == p select item).ToList().SingleOrDefault();
                    if (Mli != null)
                    {
                        CurrentMli = Mli;
                        List<MsgEntity> templist = new List<MsgEntity>(Mli.MsgList);
                        MsgList.ForEach(pa => pa.Document = new FlowDocument());
                        templist.ForEach(s => s.Document = TransContentToFace(s.MsgContent.ToString()));
                        Mli.MsgList = templist;
                        MsgList = new List<MsgEntity>(Mli.MsgList);
                        //MsgStoreEntity mse = new MsgStoreEntity();
                        //if (MsgStoreList != null)
                        //{
                        //    var data = from item in MsgStoreList where item.Mli == CurrentMli select item;
                        //    if (data != null && data.ToList().Count > 0)
                        //    {
                        //        mse = data.ToList().SingleOrDefault();
                        //        lock (Locker)
                        //        {
                        //            MsgList = mse.MsgList;
                        //        }
                        //    }
                        //}

                    }
                }));
            }
        }
        private RelayCommand _SendMsgCommand;
        /// <summary>
        /// 发送按钮
        /// </summary>
        public RelayCommand SendMsgCommand
        {
            get
            {
                return _SendMsgCommand ?? (_SendMsgCommand = new RelayCommand(() =>
                {
                    SendMsg = CombineMsgContent();
                    bool flage = WeiChat.SendToOtherMsg(SendMsg, CurrentMli.UserName);
                    CommonMethodCallBackHandlers.SendMsgCompleted += delegate (bool e)
                    {
                        flage = e;
                    };
                    if (flage)
                    {
                        MsgEntity me = new MsgEntity();
                        me.MsgContent = SendMsg;
                        me.MsgOwer = SetSendUser(CommonDefine.BaseContact.User);
                        me.MsgType = MsgTypeEnum.Text;
                        me.Document = TransContentToFace(SendMsg);
                        me.MsgOwerType = MsgOwerTypeEnum.SenderMsg;
                        for (int index = 0; index < WeChatContactsList.Count; index++)
                        {
                            if (WeChatContactsList[index].UserName == CurrentMli.UserName)
                            {
                                WeChatContactsList[index].MsgCount += 1;
                                WeChatContactsList[index].MsgList.Add(me);
                                List<MsgEntity> templist = new List<MsgEntity>(WeChatContactsList[index].MsgList);
                                MsgList.ForEach(p => p.Document = new FlowDocument());
                                templist.ForEach(p => p.Document = TransContentToFace(p.MsgContent.ToString()));
                                WeChatContactsList[index].MsgList = templist;
                                MsgList = WeChatContactsList[index].MsgList;
                                break;
                            }

                        }



                        //MsgStoreEntity mse = new MsgStoreEntity() { Mli = CurrentMli };
                        //var data = from item in MsgStoreList where item.Mli == CurrentMli select item;
                        //if (data != null && data.ToList().Count > 0)
                        //{
                        //    mse = data.ToList().SingleOrDefault();
                        //    mse.MsgList.Add(me);
                        //}
                        //else
                        //{
                        //    mse.MsgList.Add(me);
                        //    MsgStoreList.Add(mse);
                        //}
                        //lock (Locker)
                        //{
                        //    //当前联系人
                        //    MsgList.Add(me);
                        //}
                    }
                    SendMsg = "";
                    Rtb.Document.Blocks.Clear();
                    Rtb.Document.Blocks.Add(new Paragraph());

                }));
            }
        }
        private RelayCommand<string> _VoicePlayCommand = null;
        /// <summary>
        /// 播放文件
        /// </summary>
        public RelayCommand<string> VoicePlayCommand
        {
            get
            {
                return _VoicePlayCommand ?? (_VoicePlayCommand = new RelayCommand<string>((p) =>
                {
                    MediaPlayer player = new MediaPlayer();
                    player.Open(new Uri(p));
                    player.MediaEnded += delegate (object sender, EventArgs e)
                    {
                        for (int index = 0; index < MsgList.Count; index++)
                        {
                            if (MsgList[index].FilePath == p)
                            {
                                MsgList[index].HasRead = true;
                                break;
                            }
                        }
                    };
                    player.Play();
                }));
            }
        }
        private RelayCommand<string> _PlayVideoCommand;
        /// <summary>
        /// 播放语音
        /// </summary>
        public RelayCommand<string> PlayVideoCommand
        {
            get
            {
                return _PlayVideoCommand ?? (_PlayVideoCommand = new RelayCommand<string>((p) =>
                {
                    MediaElement me = new MediaElement();
                    me.Source = new Uri(p);
                    me.LoadedBehavior = MediaState.Manual;
                    me.UnloadedBehavior = MediaState.Stop;
                    me.ToolTip = "单击播放";
                    me.Height = 351;
                    me.Width = 351;
                    //me.PreviewMouseLeftButtonDown += Me_PreviewMouseLeftButtonDown;
                    me.Play();
                }));
            }
        }
        private RelayCommand<FaceImageEntity> _SelectCommand;
        /// <summary>
        /// 选择表情
        /// </summary>
        public RelayCommand<FaceImageEntity> SelectCommand
        {
            get
            {
                return _SelectCommand ?? (_SelectCommand = new RelayCommand<FaceImageEntity>((p) =>
                {
                    MsgParagraph = Rtb.Document.Blocks.FirstBlock as Paragraph;
                    if (MsgParagraph == null)
                        MsgParagraph = new Paragraph();
                    // MsgParagraph.Inlines.Add("hahhahha");
                    Image im = new Image();
                    im.Height = 30;
                    im.Width = 30;
                    im.Source = new BitmapImage(new Uri(p.FilePath));
                    MyInlineUIContainer m = new MyInlineUIContainer();
                    m.Child = im;
                    MsgParagraph.Inlines.Add(m);
                }));
            }
        }
        private RelayCommand _SendFileOrPitcureCommand;
        /// <summary>
        /// 发送图片或文件
        /// </summary>
        public RelayCommand SendFileOrPitcureCommand
        {
            get
            {
                return _SendFileOrPitcureCommand ?? (_SendFileOrPitcureCommand = new RelayCommand(() =>
                {
                    OpenFileDialog ofd = new OpenFileDialog();
                    bool? flage = ofd.ShowDialog();
                    if ((bool)flage)
                    {
                        FileInfo Fi = new FileInfo(ofd.FileName);
                        FileEntity fe = new FileEntity();
                        fe.FileName = Fi.Name;
                        fe.FileModiftTime = Fi.LastWriteTime.ToUniversalTime();
                        byte[] FileData = File.ReadAllBytes(Fi.FullName);
                        fe.DataLen = FileData.Length;
                        fe.TotalLen = FileData.Length;
                        fe.FileMd5 = GetMD5HashFromFile(ofd.FileName);
                        fe.ClientMediaId = DateTimeToosHelper.GetUnixTimeSpan() + MethodsHelper.GetThreeNumber();
                        fe.FromUserName = CommonDefine.BaseContact.User.UserName;
                        fe.ToUserName = CurrentMli.UserName;
                        fe.UploadType = 2;
                        if (Fi.Extension == ".jpg" || Fi.Extension == ".png" || Fi.Extension == ".jpeg")
                        {
                            fe.Mediatype1 = CommonDefineStrings.MediatypePitcure;// "pic";//doc
                            fe.FileType = CommonDefineStrings.Pitcure;// "image/jpeg";//文件application/octet-stream
                            fe.MediaType = MediaTypeEnum.Pitcure;
                        }
                        else
                        {
                            fe.FileType = CommonDefineStrings.Doc;
                            fe.Mediatype1 = CommonDefineStrings.MediatypeDoc;// "pic";//doc
                        }
                        WeiChat.SendFile(fe, FileData);
                    }
                }));
            }
        }
        private RelayCommand _SettingCommand = null;
        /// <summary>
        ///设置命令
        /// </summary>
        public RelayCommand SettingCommand
        {
            get
            {
                return _SettingCommand ?? (_SettingCommand = new RelayCommand(() =>
                {
                }));
            }
        }

        private RelayCommand<string> _OpenMapMsgCommand = null;
        /// <summary>
        /// 打开地图位置
        /// </summary>
        public RelayCommand<string> OpenMapMsgCommand
        {
            get
            {
                return _OpenMapMsgCommand ?? (_OpenMapMsgCommand = new RelayCommand<string>((p) =>
                {
                    Process.Start(p);
                }));
            }
        }
        #endregion

        #region 方法

        /// <summary>
        /// 保存记录
        /// </summary>
        public void SaveMsg()
        {
            string path = Environment.CurrentDirectory + "\\Data\\Msg";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            WeChatContactsList.ForEach(p =>
            {
                if (p.MsgList != null && p.MsgList.Count > 0)
                {
                    string temp = JsonConvert.SerializeObject(p.MsgList);
                    string FileName = MethodsHelper.EncryptWithMD5(p.DisplayNameDef) + ".txt";
                    File.WriteAllText(path + "\\" + FileName, temp);
                }
            });
        }
        /// <summary>
        /// 获取消息
        /// </summary>
        public void ReadMsg()
        {
            string path = Environment.CurrentDirectory + "\\Data\\Msg";
            WeChatContactsList.ForEach(p =>
            {

                string FileName = MethodsHelper.EncryptWithMD5(p.DisplayNameDef) + ".txt";
                if (File.Exists((path + "\\" + FileName)))
                {
                    string temp = File.ReadAllText(path + "\\" + FileName);
                    p.MsgList = JsonConvert.DeserializeObject<List<MsgEntity>>(temp);
                }

            });
        }
        /// <summary>
        /// 获取文件md5
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="HeadImageUrl"></param>
        private void DownloadImag(string HeadImageUrl)
        {
            //new Task(() =>
            //{
            string uuid = MethodsHelper.MsgSaveFile(DirectoryDefine.HeaderImagePath);
            HttpMethods.GetFile(UrlDefine.RootUrl + HeadImageUrl, Environment.CurrentDirectory + "\\" + DirectoryDefine.HeaderImagePath + "\\" + uuid + ".jpg", CommonDefine.Cookies);
        }
        /// <summary>
        /// 消息方法实体
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public MemberListItemEntity SetSendUser(UserEntity user)
        {
            MemberListItemEntity mli = new MemberListItemEntity();
            mli.UserName = user.UserName;
            mli.HeadUrlDef = Environment.CurrentDirectory + "\\User.jpg";// user.HeadImgUrl;
            mli.NickName = user.NickName;
            return mli;
        }
        /// <summary>
        /// 初始化数据
        /// </summary>
        public void InitData()
        {
            CommonMethodCallBackHandlers.DownLoadQRCodeCompleted += CommonMethodCallBackHandlers_DownLoadQRCodeCompleted;
            CommonMethodCallBackHandlers.LoginScranQRCodeCompleted += CommonMethodCallBackHandlers_LoginScranQRCodeCompleted;
            CommonMethodCallBackHandlers.ReceivedMsgAnalyseMsgCompleted += CommonMethodCallBackHandlers_ReceivedMsgAnalyseMsgCompleted;
            CommonMethodCallBackHandlers.LoginCompleted += CommonMethodCallBackHandlers_LoginCompleted;
            new Task(() =>
            {
                WeiChat.InitWeiChatRobot();
            }).Start();
            //AutoRepateEntity auto1 = new AutoRepateEntity() { AutoRepateType = WeChatCore.Enum.AutoRepateEnum.CommnonReply, AutoReplySwitch = "1", ReplyContent = "哈哈哈" };
            //AutoRepateEntity auto2 = new AutoRepateEntity() { AutoRepateType = WeChatCore.Enum.AutoRepateEnum.ThanksReply, AutoReplySwitch = "0", ReplyContent = "回复" };
            //List<AutoRepateEntity> oo = new List<AutoRepateEntity>();
            //oo.Add(auto1);
            //oo.Add(auto2);
            //string str = JsonConvert.SerializeObject(oo);
            //File.WriteAllText("1.json", str);
            //oo = new List<AutoRepateEntity>();
            //oo = JsonConvert.DeserializeObject<List<AutoRepateEntity>>(str);
            Faces = XMLHelper.DESerializer<Face>(File.ReadAllText(Environment.CurrentDirectory + "\\Data\\Face.xml"));
        }

        private void CommonMethodCallBackHandlers_LoginCompleted(bool obj)
        {
            if (obj)
            {
                PageNumber = 1;
                PageCount = 10;
                //登录成功,展示主页面
                QRCodeVisibilty = Visibility.Collapsed;
                PersonChecked = true;//默认初始化个人联系人
                ContentVisibilty = Visibility.Visible;
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    ReadMsg();
                }));
            }
        }
        /// <summary>
        /// 选择下一页的数据
        /// </summary>
        /// <param name="step"></param>
        public void SelectNextPage(int step)
        {
            PageNumber += step;
            List<MemberListItemEntity> list = WeiChat.SetSplite(CtType);//.Skip(PageNumber * PageCount).Take(PageCount).ToList();
            WeChatContactsList = list;
        }
        private void CommonMethodCallBackHandlers_LoginScranQRCodeCompleted(string obj)
        {
            //扫描
            ImagePath = obj;
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                LoginImageSource = new BitmapImage(new Uri(obj));
            }));
        }

        private void CommonMethodCallBackHandlers_DownLoadQRCodeCompleted()
        {
            //下载微信二维码成功
            ImagePath = Environment.CurrentDirectory + "\\Check.jpg";
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                LoginImageSource = new BitmapImage(new Uri(Environment.CurrentDirectory + "\\Check.jpg"));
            }));
        }
        /// <summary>
        /// 消息回调
        /// </summary>
        /// <param name="obj"></param>
        private void CommonMethodCallBackHandlers_ReceivedMsgAnalyseMsgCompleted(MsgEntity obj)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
              {

                  for (int index = 0; index < WeChatContactsList.Count; index++)
                  {
                      if (WeChatContactsList[index].UserName == obj.MsgOwer.UserName)
                      {
                          WeChatContactsList[index].MsgCount += 1;
                          if (obj.MsgType == MsgTypeEnum.Text)
                              obj.Document = TransContentToFace(obj.MsgContent.ToString());
                          WeChatContactsList[index].MsgList.Add(obj);
                          if (obj.MsgOwer.UserName == CurrentMli.UserName)
                          {
                              List<MsgEntity> templist = new List<MsgEntity>(WeChatContactsList[index].MsgList);
                              MsgList.ForEach(p => p.Document = new FlowDocument());
                              templist.ForEach(p => p.Document = TransContentToFace(p.MsgContent.ToString()));
                              WeChatContactsList[index].MsgList = templist;
                              MsgList = null;
                              MsgList = WeChatContactsList[index].MsgList;
                          }
                      }
                  }
                  var data = WeChatContactsList.OrderBy(p => p.MsgCount).ToList();
                  WeChatContactsList = new List<MemberListItemEntity>(data);
                  //非当前联系人
                  //MsgStoreEntity mse = new MsgStoreEntity() { Mli = obj.MsgOwer };
                  //var data = from item in MsgStoreList where item.Mli == obj.MsgOwer select item;
                  //if (data != null && data.ToList().Count > 0)
                  //{
                  //    mse = data.ToList().SingleOrDefault();
                  //    mse.MsgList.Add(obj);
                  //}
                  //else
                  //{
                  //    mse.MsgList.Add(obj);
                  //    MsgStoreList.Add(mse);
                  //}
              }));

            ////收到消息
            //if (obj.MsgOwer == CurrentMli)
            //{
            //    Application.Current.Dispatcher.Invoke(new Action(() =>
            //    {
            //        lock (Locker)
            //        {
            //            //当前联系人
            //            MsgList.Add(obj);
            //        }
            //    }));
            //}

        }
        string path = "pack://application:,,,/WindowsWeChat;component/Resource/Face/{0}";
        /// <summary>
        /// 封装消息体
        /// </summary>
        /// <returns></returns>
        public string CombineMsgContent()
        {
            string param = "";
            MsgParagraph = Rtb.Document.Blocks.FirstBlock as Paragraph;
            if (MsgParagraph == null)
                return param;
            InlineCollection ic = MsgParagraph.Inlines;
            MyInlineUIContainer mic = new MyInlineUIContainer();
            Run R = new Run();
            foreach (var c in ic)
            {
                mic = c as MyInlineUIContainer;
                R = c as Run;
                if (mic != null)
                {
                    if (mic.InlineType == InlineUIContainerType.Image)
                    {
                        if ((mic.Child as Image) != null)
                        {
                            var data = from item in Faces.FaceList where string.Format(path, item.FilePath) == (mic.Child as Image).Source.ToString() select item;
                            if (data != null && data.ToList().Count > 0)
                                param = param + "[" + data.ToList().SingleOrDefault().FileName + "]";
                        }
                    }
                }
                if (R != null)
                {
                    param += R.Text;
                }
                //if ((c as Run) != null)
                //    Console.WriteLine((c as Run).Text);
            }
            return param;
        }

        #region CobineMsgToFace
        /// <summary>
        /// 转义消息体中的表情符号
        /// </summary>
        /// <param name="MsgContents"></param>
        public FlowDocument TransContentToFace(string MsgContents)
        {
            FlowDocument Fd = new FlowDocument();
            Paragraph MsgParagraph = new Paragraph();
            //string cont = "[大哭][微笑][微笑][微笑][微笑][微笑]倒萨大[的倒]萨大[色]微[微笑][害羞][微笑]笑[微笑]";
            char[] temp = MsgContents.ToCharArray();
            string MsgContentBody = "";
            string MsgFaceBody = "";
            bool flage = false;
            for (int index = 0; index < temp.Length; index++)
            {
                Console.WriteLine(temp[index].ToString());
                string b = temp[index].ToString();
                if (b == "[")
                {
                    flage = true;
                }
                if (!flage)
                {
                    MsgContentBody += b;
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(MsgContentBody))
                    {
                        MsgParagraph.Inlines.Add(MsgContentBody);
                        MsgContentBody = "";
                    }
                    MsgFaceBody += b;
                    if (b == "]")
                    {
                        if (!string.IsNullOrWhiteSpace(MsgFaceBody))
                        {
                            Image im = new Image();
                            im.Height = 30;
                            im.Width = 30;
                            var datassss = from item in Faces.FaceList where "[" + item.FileName + "]" == MsgFaceBody select item;
                            FaceItem fi = datassss.ToList().SingleOrDefault();
                            if (fi == null)
                            {
                                MsgContentBody += MsgFaceBody;
                                MsgFaceBody = "";
                                flage = false;
                                continue;
                            }
                            im.Source = new BitmapImage(new Uri(string.Format(path, fi.FilePath)));
                            MyInlineUIContainer m = new MyInlineUIContainer();
                            m.Child = im;
                            MsgParagraph.Inlines.Add(m);
                            flage = false;
                            MsgFaceBody = "";
                        }
                    }

                }
            }
            if (!string.IsNullOrWhiteSpace(MsgContentBody))
            {
                MsgParagraph.Inlines.Add(MsgContentBody);
                MsgContentBody = "";
            }
            Fd.Blocks.Add(MsgParagraph);
            return Fd;
        }
        #endregion

        #endregion

    }
}
